<template>
  <div class="book-list-container">
    <el-card class="book-list-card">
    <el-form :inline="true" :model="queryForm" class="demo-form-inline">
      <el-form-item label="书名">
        <el-input v-model="queryForm.bookname" placeholder="请输入书名"></el-input>
      </el-form-item>
      <el-form-item label="作者">
        <el-input v-model="queryForm.author" placeholder="请输入作者"></el-input>
      </el-form-item>
      <el-form-item label="出版日期">
        <el-date-picker
          v-model="queryForm.publishDate"
          type="date"
          placeholder="选择出版日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchBooks">查询</el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="addDialogVisible = true" >新增图书</el-button>
    <el-table :data="books" stripe>
      <!--<el-table-column prop="id" label="ID"></el-table-column>-->
      <el-table-column prop="bookname" label="书名"></el-table-column>
      <el-table-column prop="author" label="作者"></el-table-column>
      <el-table-column prop="publisher" label="出版社"></el-table-column>
      <el-table-column prop="publishDate" label="出版日期"></el-table-column>
      <el-table-column prop="stock" label="库存数量"></el-table-column>
      <el-table-column prop="storageTime" label="入库时间"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="editDialogVisible = true; editBook = { ...scope.row }">编辑</el-button>
          <el-button type="danger" size="mini" @click="deleteBook(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <el-dialog :visible.sync="addDialogVisible" title="新增图书">
      <el-form :model="addBook" ref="addForm" :rules="bookRules"  label-width="80px">
        <el-form-item prop="bookname" label="书名">
          <el-input v-model="addBook.bookname"></el-input>
        </el-form-item>
        <el-form-item prop="author" label="作者">
          <el-input v-model="addBook.author"></el-input>
        </el-form-item>
        <el-form-item label="出版社">
          <el-input v-model="addBook.publisher"></el-input>
        </el-form-item>
        <el-form-item prop="publishDate" label="出版日期">
          <el-date-picker
            v-model="addBook.publishDate"
            type="datetime"
            placeholder="选择出版日期"
            style="width: 100%;"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="库存数量">
          <el-input v-model.number="addBook.stock"></el-input>
        </el-form-item>
        <el-form-item prop="storageTime" label="入库时间">
          <el-date-picker
            v-model="addBook.storageTime"
            type="datetime"
            placeholder="选择入库时间"
            style="width: 100%;"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addBookSubmit">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="editDialogVisible" title="编辑图书">
      <el-form :model="editBook" ref="editForm" :rules="bookRules" label-width="80px">
        <el-form-item prop="bookname" label="书名">
          <el-input v-model="editBook.bookname"></el-input>
        </el-form-item>
        <el-form-item prop="author" label="作者">
          <el-input v-model="editBook.author"></el-input>
        </el-form-item>
        <el-form-item label="出版社">
          <el-input v-model="editBook.publisher"></el-input>
        </el-form-item>
        <el-form-item prop="publishDate" label="出版日期">
          <el-date-picker
            v-model="editBook.publishDate"
            type="datetime"
            placeholder="选择出版日期"
            style="width: 100%;"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="库存数量">
          <el-input v-model.number="editBook.stock"></el-input>
        </el-form-item>
        <el-form-item prop="storageTime" label="入库时间">
          <el-date-picker
            v-model="editBook.storageTime"
            type="datetime"
            placeholder="选择入库时间"
            style="width: 100%;"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editBookSubmit">确定</el-button>
      </div>
    </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      books: [],
      queryForm: {
        bookname: '',
        author: '',
        publishDate: '',
      },
      currentPage: 1,
      pageSize: 10,
      total: 0,
      addDialogVisible: false,
      addBook: {
        bookname: '',
        author: '',
        publisher: '',
        publishDate: '',
        stock: 0,
        storageTime: '',
      },
      editDialogVisible: false,
      editBook: {},
      bookRules: {
        bookname: [
          { required: true, message: '书名不能为空', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '作者不能为空', trigger: 'blur' }
        ],
        publishDate: [
          { required: true, message: '出版日期不能为空', trigger: 'blur' }
        ],
        storageTime: [
          { required: true, message: '入库时间不能为空', trigger: 'blur' }
        ]
      },
    };
  },
  mounted() {
    this.fetchBooks();
  },
  methods: {
    async fetchBooks() {
      try {
        const response = await this.$axios.get('/api/books', {
          params: {
            pageNum: this.currentPage,
            pageSize: this.pageSize,
            ...this.queryForm,
          },
          headers: {
            'Authorization': `Bearer ${this.$store.getters.getAccessToken}`
          }
        });
        if (response.data.code === 200) {
          this.books = response.data.data.records;
          this.total = response.data.data.total;
        }else {
          this.$message.error(response.data.msg);
        }

      } catch (error) {
        this.$message.error('获取图书列表失败，'+error.response.data.msg);
      }
    },
    async addBookSubmit() {
      let flag = false;
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          flag = true;
        }
      });
      if (flag) {
      try {
        const response = await this.$axios.post('/api/books/add', this.addBook,{
          headers: {
            'Authorization': `Bearer ${this.$store.getters.getAccessToken}`
          }
        });
        if (response.data.code === 200) {
          this.addDialogVisible = false;
          this.fetchBooks();
          this.$message.success('新增图书成功');
        } else {
          this.$message.error(response.data.msg);
        }

      } catch (error) {
        this.$message.error('新增图书失败，'+error.response.data.msg);
      }
    }
    },
    async editBookSubmit() {
      let flag = false;
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          flag = true;
        }
      });
      if(flag){
      try {
        await this.$axios.put(`/api/books/${this.editBook.id}`, this.editBook,{
          headers: {
            'Authorization': `Bearer ${this.$store.getters.getAccessToken}`
          }
        });
        this.editDialogVisible = false;
        this.fetchBooks();
        this.$message.success('编辑图书成功');
      } catch (error) {
        this.$message.error('编辑图书失败，'+error.response.data.msg);
      }
      }
    },
    async deleteBook(id) {
      try {
        await this.$axios.delete(`/api/books/${id}`,{
          headers: {
            'Authorization': `Bearer ${this.$store.getters.getAccessToken}`
          }
        });
        this.fetchBooks();
        this.$message.success('删除图书成功');
      } catch (error) {
        this.$message.error('删除图书失败，'+error.response.data.msg);
      }
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchBooks();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchBooks();
    },
  },
};
</script>
<style scoped>
  .book-list-container {
    padding: 20px;
    background-color: white;
  }

  .book-list-card {
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    border-radius: 5px;
  }

  .book-list-header {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-bottom: 20px;
  }
</style>